<?php
namespace Duobao\Model;

use Think\Model;
use Duobao\Model\MemberModel as Member;
use Duobao\Controller\LogController as Mylog;

class ShoplistModel extends Model
{

    protected $tableName = 'shoplist';

    /**
     * banner图片数据
     *
     * @return Ambigous <boolean, multitype:string unknown Ambigous <string, unknown> Ambigous <> >
     */
    public function getBannerData()
    {
        #$wapObj = D('wap');
        $model = new \Think\Model();
        #banner图的连接跳到能购买的那一期
        $slidesList = $model->table('__WAP__')->select();

        $slides = false;
        
        if ($slidesList) {
            foreach ($slidesList as $item) {
                $tmp = array();
                $tmp['title'] = $item['title'];
                $tmp['backGroudColor'] = $item['color'];
                $tmp['imgUrl'] = C('CDN_DOMAIN') . C('UPLOAD_PATH') . $item['img'];

                #获取当前商品的最新一期的商品
                if($item['link']){
                    $where['id'] = $item['link'];
                    $sid = $model->table('__SHOPLIST__')->where($where)->getField('sid');
                    #获取当前cateid的最大id值
                    $where2['sid'] = $sid;
                    $id = $model->table("__SHOPLIST__")->where($where2)->order('id desc')->limit(1)->getField('id');
                    $tmp['id'] = $id;
                }else{
                    $tmp['id'] = '';
                }

                #$item['link'] ? $item['link'] : "";
                #Mylog::write("banner:".$tmp['id']);
                $slides[] = $tmp;
            }
        }
        return $slides;
    }

    /**
     * 最新揭晓数据
     *
     * @return Ambigous <boolean, multitype:string unknown NULL >
     */
    public function getLatestAnnouncementData()
    {
        $shoplistObj = $this;
        
        $where = array();
        $where['q_end_time'] = array(
            'neq',
            ''
        );
        $where['q_showtime'] = 'N';
        
        $shopLists = $shoplistObj->where($where)
            ->order('`q_end_time` DESC ')
            ->limit(3)
            ->select();
        
        $list = false;
        
        if ($shopLists) {
            $memberObj = new Member();
            
            foreach ($shopLists as $item) {
                $tmp = array();
                $tmp['shopid'] = $item['id'];
                $tmp['shopTitle'] = $item['title'];
                $tmp['thumb'] = C('CDN_DOMAIN') . C('UPLOAD_PATH') . $item['thumb'];
                $tmp['userid'] = $item['q_uid'];
                $tmp['username'] = $memberObj->getShowName($item['q_uid']);
                
                $list[] = $tmp;
            }
        }
        return $list;
    }

    /**
     * 热门推荐数据
     *
     * @return Ambigous <boolean, multitype:string unknown >
     */
    public function getPopularShopData()
    {
        $shoplistObj = $this;
        
        $where = array();
        $where['renqi'] = '1';
        $where['q_end_time'] = array(
            'exp',
            ' is null '
        );
        $shopLists = $shoplistObj->where($where)
            ->order('`id` DESC')
            ->limit(16)
            ->select();
        
        $list = false;
        
        if ($shopLists) {
            
            foreach ($shopLists as $item) {
                $tmp = array();
                $tmp['shopid'] = $item['id'];
                $tmp['shopTitle'] = $item['title'];
                $tmp['thumb'] = C('CDN_DOMAIN') . C('UPLOAD_PATH') . $item['thumb'];
                $tmp['price'] = $item['money'];
                $tmp['currentNum'] = $item['canyurenshu'];
                $tmp['totalNum'] = $item['zongrenshu'];
                
                $list[] = $tmp;
            }
            
            // 凑成偶数
            $total = count($list);
            if ($total % 2 == 1) {
                array_pop($list);
            }
        }
        
        return $list;
    }

    /**
     * 获取今日限购数据数据
     */
    public function getTimeLimitedBuyingData()
    {
        $model = new \Think\Model();
        
        $w_jinri_time = strtotime(date('Y-m-d'));
        $w_minri_time = strtotime(date('Y-m-d', strtotime("+1 day")));
        
        
        $shopLists = $model->query("select * from `__PREFIX__shoplist` where `xsjx_time` > '$w_jinri_time' and `xsjx_time` < '$w_minri_time' order by xsjx_time limit 0,3 ");
        
        if ($shopLists) {
            
            foreach ($shopLists as $item) {
                $tmp = array();
                $tmp['shopid'] = $item['id'];
                $tmp['shopTitle'] = $item['title'];
                $tmp['thumb'] = C('CDN_DOMAIN') . C('UPLOAD_PATH') . $item['thumb'];
                $tmp['price'] = $item['money'];
                $tmp['open_time'] = $item['xsjx_time'];
                $tmp['currentNum'] = $item['canyurenshu'];
                $tmp['totalNum'] = $item['zongrenshu'];
                
                $list[] = $tmp;
            }
        }
        
        return $list;
    }

    /**
     * 获取最新商品的数据,3条数据
     */
    public function getNewGoods(){
        $model = new \Think\Model();
        #$shoplist = $model->query("select thumb,id,title from `__PREFIX__shoplist` WHERE `q_uid` IS NULL GROUP BY `sid` ORDER BY `time` DESC  limit 0,3");
        $shoplist = $model->query("select thumb,id,title from `__PREFIX__shoplist` WHERE `q_uid` IS NULL  AND `newpos` = 1 GROUP BY `sid` ORDER BY `time` DESC  limit 0,3");

        if($shoplist){
            $tmp = array();
            foreach($shoplist as $item){
                $tmp['id'] = $item['id'];
                $tmp['img'] = C('CDN_DOMAIN') . C('UPLOAD_PATH').$item['thumb'];
                $tmp['goodsName'] = $item['title'];

                $list[] = $tmp;
            }
        }

        return $list;
    }

    /**
     * 获取全部商品的数据
     * 显示剩余人数大于0的数据
     * $category :商品所属类别
     * $order 商品的排序：1->人气 2->最新 3->剩余人数
     */
    public  function getAllgoods($category='0',$offset='0',$length=10,$ordername=1){
        $shoplistObj = $this;
        $where=array();
        $where['shenyurenshu']=array('gt',0);

        switch ($ordername){
            case 1:
                $ordername="renqi";
                break;
            case 2:
                $ordername='time desc';
                break;
            case 3:
                $ordername='shenyurenshu asc';
                break;
        }


        if($category==0) {
                $shopLists = $shoplistObj->where($where)->order($ordername)->limit($offset, $length)->select();

                $list = false;

                if ($shopLists) {

                    $tmp = array();
                    foreach ($shopLists as $item) {
                        $tmp = array();
                        $tmp['shopid'] = $item['id'];
                        $tmp['shopTitle'] = $item['title'];
                        $tmp['thumb'] = C('CDN_DOMAIN') . C('UPLOAD_PATH') . $item['thumb'];
                        $tmp['price'] = $item['money'];
                        $tmp['open_time'] = $item['xsjx_time'];
                        $tmp['currentNum'] = $item['canyurenshu'];
                        $tmp['totalNum'] = $item['zongrenshu'];
                        $tmp['cateid'] = $item['cateid'];

                        $list[] = $tmp;
                    }
                }
        }else{
            $where['cateid']=$category;
            $shopLists = $shoplistObj->where($where)->order($ordername)->limit($offset, $length)->select();

            $list = false;

            if ($shopLists) {

                $tmp = array();
                foreach ($shopLists as $item) {
                    $tmp = array();
                    $tmp['shopid'] = $item['id'];
                    $tmp['shopTitle'] = $item['title'];
                    $tmp['thumb'] = C('CDN_DOMAIN') . C('UPLOAD_PATH') . $item['thumb'];
                    $tmp['price'] = $item['money'];
                    $tmp['open_time'] = $item['xsjx_time'];
                    $tmp['currentNum'] = $item['canyurenshu'];
                    $tmp['totalNum'] = $item['zongrenshu'];
                    $tmp['cateid'] = $item['cateid'];

                    $list[] = $tmp;
                }
            }
        }
        #$model = new \Think\Model();
        #Mylog::write($model->getLastSql());

        return $list;
    }

    /**
     * 总人数排序
     * category:商品的类别
     * order :排序规则 desc 和asc
     */
    public function orderByTotalNumber( $category='0',$offset='',$length=10,$order='desc'){
        $shoplistObj = $this;
        $where=array();
        $where['shenyurenshu']=array('gt',0);

        if($category==0) {
            $shopLists = $shoplistObj->where($where)->order("zongrenshu $order")->limit($offset, $length)->select();

            $list = false;

            if ($shopLists) {

                $tmp = array();
                foreach ($shopLists as $item) {
                    $tmp = array();
                    $tmp['shopid'] = $item['id'];
                    $tmp['shopTitle'] = $item['title'];
                    $tmp['thumb'] = C('CDN_DOMAIN') . C('UPLOAD_PATH') . $item['thumb'];
                    $tmp['price'] = $item['money'];
                    $tmp['open_time'] = $item['xsjx_time'];
                    $tmp['currentNum'] = $item['canyurenshu'];
                    $tmp['totalNum'] = $item['zongrenshu'];

                    $list[] = $tmp;
                }
            }
        }else{
            $where['cateid']=$category;
            $shopLists = $shoplistObj->where($where)->order("zongrenshu $order")->limit($offset, $length)->select();

            $list = false;

            if ($shopLists) {

                $tmp = array();
                foreach ($shopLists as $item) {
                    $tmp = array();
                    $tmp['shopid'] = $item['id'];
                    $tmp['shopTitle'] = $item['title'];
                    $tmp['thumb'] = C('CDN_DOMAIN') . C('UPLOAD_PATH') . $item['thumb'];
                    $tmp['price'] = $item['money'];
                    $tmp['open_time'] = $item['xsjx_time'];
                    $tmp['currentNum'] = $item['canyurenshu'];
                    $tmp['totalNum'] = $item['zongrenshu'];

                    $list[] = $tmp;
                }
            }
        }
        return $list;
    }


    /**
     * 根据商品的id获取商品,获取商品的信息，和当前商品的是否揭晓的数据，以及揭晓的时间
     * 2中状态，1，没有开奖，显示商品参与的进度，2，已揭晓显示用户的中奖信息
     */
    public function getGoodsById($id=''){
        $model = new \Think\Model();

        $goods = $model->query("select * from `__PREFIX__shoplist` where `id` = '$id'");


        $ret = array();
        if($goods){
                #两种状态，1，没有揭晓，显示商品的信息包括商品的商品的id，图片，商品名，期号，总需人数，剩余人数
                #2、已经揭晓，id,商品图片，商品的名，期号，中奖人名，中奖ip，中奖用户id，参与人次，中奖者购买的号码，揭晓时间，中奖号码
            #状态1
            #判断是否揭晓
            if($goods[0]['q_end_time']){
                #已揭晓
                $ret['status'] = 'alreadyAnnounced';#进行中
                $winUser = $model->query("select username,uphoto,uid,gonumber,goucode,huode,ip FROM `__PREFIX__member_go_record` where uid = ".$goods[0]['q_uid']." and shopid =".$goods[0]['id'] );
                $tmp = array();
                $tmp['shopid'] = $goods[0]['id'];#商品id
                $tmp['shopTitle'] = $goods[0]['title'];#商品名称
                $tmp['thumb'] = C('CDN_DOMAIN') . C('UPLOAD_PATH') . $goods[0]['thumb'];//商品的图片
                $tmp['periods'] = $goods[0]['qishu'];//商品的期数
                $tmp['winLucklyCode'] = $goods[0]['q_user_code'];//获奖者的中奖号码
                $tmp['winUserId'] = $goods[0]['q_uid'];//获奖者的id
                $tmp['endTime'] = date("Y-m-d H:i:s",$goods[0]['q_end_time']);#揭晓时间
                $tmp['recordStartTime'] = date("Y-m-d H:i:s",$goods[0]['time']);#参与记录的开始时间

                $tmp['winUserImg'] = $winUser[0]['uphoto'];//获奖者的图片
                $tmp['winName'] = $winUser[0]['username'];//用户的名称
                $tmp['winIp'] = $winUser[0]['ip'];//用户ip地址

                foreach($winUser as $item){
                    $tmp['winBuyNum'] += $item['gonumber'];//获奖者购买次数
                    $tmp['winBuyCode'] .= $item['goucode'].',';//获奖者购买的code
                }
                $ret['message'] = $tmp;
            }else{
                #未揭晓，可以参与,不需要查找数据库
                $ret['status'] = 'underway';#进行中
                $tmp = array();
                foreach($goods as $item){
                    $tmp['shopid'] = $goods[0]['id'];#商品id
                    $tmp['shopTitle'] = $goods[0]['title'];#商品名称
                    $tmp['thumb'] = C('CDN_DOMAIN') . C('UPLOAD_PATH') . $goods[0]['thumb'];//商品的图片
                    $tmp['periods'] = $goods[0]['qishu'];//商品的期数
                    $tmp['recordStartTime'] = date("Y-m-d H:i:s",$goods[0]['time']);#参与记录的开始时间
                    $tmp['remainderNum'] = $item['shenyurenshu'];//剩余人数
                    $tmp['totalNum'] = $item['zongrenshu']; //总需人数
                }

                $ret['message'] = $tmp;
            }
        }else{
            return false;
        }


        return $ret;
    }

    /**
     * 根据商品id获取商品的详情
     */
    public function getGoodContentById($id=''){
        $goodsObj = $this;

        $where = array();
        $where['id']=$id;
        $goods = $goodsObj->where($where)->getField("content");

        return $goods;
    }

    /**
     * 获取商品类别
     */
    public function getGoodsCategory(){
        $model = new \Think\Model();

        $category = $model->query("select __PREFIX__category.name,__PREFIX__category.cateid from __PREFIX__category WHERE __PREFIX__category.parentid = 0 AND  __PREFIX__category.model = 1");

        if($category){

            $tmp = array();
            foreach($category as $item){
                $tmp['category_name'] = $item['name'];
                $tmp['category_id'] = $item['cateid'];
                $list[] = $tmp;
            }
        }

        return $list;
    }

    /**
     * 根据商品的期号获取商品的sid
     * series :期号
     */
    public function getSidBySeries($series){
        $where = array();
        $where['qishu'] = $series;

        $sid = $this->where($where)->getField(sid);

        if($sid){
            return $sid;
        }else{
            return '';
        }
    }

    /**
     * 进入商品的页面的往期揭晓
     * 参数商品id
     * 获取除了当前的id之外的并已经揭晓的数据 数据库字段存在q_uid,中奖人id
     */
    public function previousRecord($id){
        $shoplist = $this;
        $condition = array();
        $condition['id'] = $id;
        $model = new \Think\Model();

        #要实现往期获奖需要首先自连接查询，在与member_go_record 连接，分为两次查询
        #获取当前商品的sid，再连接查询
        $sid = $shoplist->where($condition)->getField('sid');

        #更具sid获取往期中奖的信息
        $record = $model->query("select __PREFIX__shoplist.id,__PREFIX__shoplist.qishu,__PREFIX__shoplist.q_end_time,__PREFIX__shoplist.q_uid,__PREFIX__shoplist.q_user_code,__PREFIX__member_go_record.username,__PREFIX__member_go_record.uphoto,__PREFIX__member_go_record.gonumber,__PREFIX__member_go_record.ip from __PREFIX__shoplist INNER JOIN __PREFIX__member_go_record ON  __PREFIX__member_go_record.shopqishu = __PREFIX__shoplist.qishu AND __PREFIX__member_go_record.huode = __PREFIX__shoplist.q_user_code WHERE __PREFIX__shoplist.sid='$sid' ORDER BY __PREFIX__shoplist.qishu DESC ");

        if($record){

            $tmp =array();
            foreach($record as $item){
                $tmp['sid'] = $item['id'];//商品的上级id
                $tmp['periodsNo'] = $item['qishu'];//商品的期数
                $tmp['announcedTime'] = date("Y-m-d H:i:s",$item['q_end_time']);//揭晓时间
                $tmp['userid'] =  $item['q_uid'];//获奖用户id
                $tmp['usercode'] = $item['q_user_code'];//中奖号码
                $tmp['username'] = $item['username'];//用户名
                $tmp['userimg'] = $item['uphoto'];//用户头像
                #修改因为中奖的用户可能在一期中参与了多次，统计用户参与的次数
                #定义条件
                $count = $model->query("select SUM(__PREFIX__member_go_record.gonumber) as gonumber from __PREFIX__member_go_record where __PREFIX__member_go_record.uid =".$item['q_uid']." and __PREFIX__member_go_record.shopid = ".$tmp['sid']." AND __PREFIX__member_go_record.shopqishu =".$item['qishu'])[0]['gonumber'];
                #Mylog::write($model->getLastSql());
                $tmp['personTimes'] = $count;//参与人次
                $tmp['userip'] = $item['ip'];//用户ip

                $list[] = $tmp;
            }
        }
        return $list;


    }

    /**
     * 查看揭晓商品的详情
     */
    public function checkCalculateDetail($gid){
        $is_announced = $this->query("select id,q_uid,q_end_time,zongrenshu from __PREFIX__shoplist where id = $gid");
        #判断商品是否存在
        if($is_announced){
            #判断商品是否已经揭晓
            if($is_announced[0]['q_uid']){
                #获取揭晓时间end_time,并获取揭晓时间前的50个全站购买记录
                $model = new \Think\Model();
                $buy_item = $model->query("select __PREFIX__member_go_record.time,__PREFIX__member_go_record.username from __PREFIX__member_go_record WHERE `time` <". $is_announced[0]['q_end_time']." ORDER BY __PREFIX__member_go_record.time DESC limit 50");
                #计算时间总和
                $time_sum = 0;
                $ret['item'] = array();
                foreach($buy_item as $key => $item){
                    $time = date("His",$item['time']);
                    $ret['item'][$key]['time'] = date('Y-m-d H:i:s',$item['time']);
                    $ret['item'][$key]['username'] = $item['username'];
                    #$ret['item'][$key]['timestamp'] = $item['time'];
                    #分割字符串,获取时间戳后的随机数
                    $rand_number = explode('.',$item['time']);
                    $ret['item'][$key]['time'] .= ".".$rand_number[1];
                    #转换整型计算时间和
                    $time_sum += intval($time.$rand_number[1]);
                    $ret['item'][$key]['number'] = intval($time.$rand_number[1]);
                }
                #封装数组
                #计算中奖号码
                $luckly_number =fmod($time_sum , $is_announced[0]['zongrenshu'])+10000001;
                $ret['time_sum'] = $time_sum;
                $ret['luckly_number'] = $luckly_number;

                return $ret;
            }else{
                return false;#商品未揭晓
            }
        }else{
            return false;#商品不存在返回false
        }
    }

    /* end of shop list model */
}